package org.ithang.system.data.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.ithang.application.bcAddr.bean.BcAddr;
import org.ithang.application.bcAddr.service.BcAddrService;
import org.ithang.application.operationLog.bean.OperationLog;
import org.ithang.application.operationLog.service.OperationLogService;
import org.ithang.system.data.bean.SysInfo;
import org.ithang.system.data.service.DataService;
import org.ithang.system.keyvalue.bean.Keyvalue;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.system.sysLog.bean.SysLog;
import org.ithang.system.sysLog.service.SysLogService;
import org.ithang.system.user.bean.User;
import org.ithang.tools.database.Dao;
import org.ithang.tools.eth.ETHInfo;
import org.ithang.tools.eth.ETHUtil;
import org.ithang.tools.gener.CodeGener;
import org.ithang.tools.gener.TableInfo;
import org.ithang.tools.lang.DateUtils;
import org.ithang.tools.lang.JsonUtils;
import org.ithang.tools.lang.MacUtil;
import org.ithang.tools.lang.StrUtils;
import org.ithang.tools.model.Action;
import org.ithang.tools.model.ActionResult;
import org.ithang.tools.model.ErrorInfo;
import org.ithang.tools.redis.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 系统数据维护功能
 * 包括:
 * 系统安装初始化与升级
 * 菜单管理
 * 表结构管理
 * @author zyt
 *
 */
@Controller
@RequestMapping("sys/data")
public class DataAction extends Action<Object>{

	@Autowired
	private KeyvalueService keyvalueService;
	
	@Autowired
	private BcAddrService bcAddrService;
	
	@Autowired
	private OperationLogService operationLogService;
	
	@Autowired
	private DataService dataService;
	
	@Autowired
	private SysLogService sysLogService;
	
	private static Thread gasThread=null;
	private static Thread goverThread=null;
	
	@RequestMapping(value="info",method=RequestMethod.GET)
	public ActionResult info(){
		SysInfo info=dataService.info();
		return page("info",info);
	}
	
	@RequestMapping(value="tables",method=RequestMethod.GET)
	public String tables(){
		return "system/data/tables";
	}
	
	@ResponseBody
	@RequestMapping(value="tables",method=RequestMethod.POST)
	public Map<String,Object> tables(String table){
		List<TableInfo> tables=dataService.tables(table);
		Map<String,Object> result=new HashMap<>();
		result.put("total", tables.size());
		result.put("rows", tables);
		return result;
	}
	
	/**
	 * 根据表名生成代码
	 * @param tables
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="gencode",method=RequestMethod.POST)
	public ActionResult generCode(String[] tables){
		try{
		    CodeGener cdGener=new CodeGener(Dao.getDataSource());
		    cdGener.gener(tables);
		}catch(Exception e){
			e.printStackTrace();
		    return error(ErrorInfo.InternalError);
		}
		return success();
	}
	
	
	@ResponseBody
	@RequestMapping(value="gas",method=RequestMethod.POST)
	public ActionResult gas(){
		try{
		   
			Keyvalue gas=keyvalueService.get(Keys.Gas);
			if(null==gas||gas.doubleValue()<=0){
				return error(ErrorInfo.BalanceNotEnoughError);
			}
			
			if(null!=gasThread&&gasThread.isAlive()){
				return error(ErrorInfo.GasingError);
			}
			
			Keyvalue gasBalance=keyvalueService.get(Keys.GasBalance);
			
			gasThread=new Thread(new Runnable(){
				@Override
				public void run() {

					//发gas
					List<String> addrs=keyvalueService.listsStr("select addr from bc_addr");
					

						boolean test=false;
							    Keyvalue kv=keyvalueService.get(Keys.TestDev);
							    if(null!=kv&&1==kv.intValue()){
							    	test=true;
							    }
					
					for(String addr:addrs){
						try{
							double balance=ETHUtil.getTokenBalance(addr,test);
							
							if(balance>=gasBalance.doubleValue()){
								ETHInfo info=ETHUtil.transferETH(StrUtils.dhx(keyvalueService.getKPrikey()), addr, gas.doubleValue());
								 if(null!=info){
								    	SysLog log=new SysLog();
								    	log.setSlog(JsonUtils.toJsonStr(info));
								    	log.setCtime(DateUtils.getSystime());
								    	sysLogService.add(log);
								  }
							}
						}catch(Exception e){
							e.printStackTrace();
							SysLog log=new SysLog();
					    	log.setSlog(e.getMessage());
					    	
					    	
					    	
					    	log.setCtime(DateUtils.getSystime());
					    	sysLogService.add(log);
						}
					}
				}
			});
			gasThread.start();
			
		}catch(Exception e){
			e.printStackTrace();
		    return error(ErrorInfo.InternalError);
		}
		return success();
	}
	
	/**
	 * 归集
	 */
	@ResponseBody
	@RequestMapping(value="gover",method=RequestMethod.POST)
	public ActionResult gover(HttpServletRequest request){
		
		if(null!=goverThread&&goverThread.isAlive()){
			return error(ErrorInfo.GoveringError);
		}
		try{
			goverThread=new Thread(new Runnable(){
				@Override
				public void run() {
					//归集
					List<BcAddr> addrs=bcAddrService.list();
					

					boolean test=false;
						    Keyvalue kv=keyvalueService.get(Keys.TestDev);
						    if(null!=kv&&1==kv.intValue()){
						    	test=true;
						    }
					
					for(BcAddr addr:addrs){
						try{
						    double balance=ETHUtil.getTokenBalance(addr.getAddr(),test);
						    if(0==balance){
						    	continue;
						    }
						    ETHInfo info=ETHUtil.transfer(StrUtils.dhx(addr.getPrivate_key()), keyvalueService.getInAddr(), balance,test);
						    if(null!=info){
						    	SysLog log=new SysLog();
						    	log.setSlog(JsonUtils.toJsonStr(info));
						    	log.setFrom_addr(addr.getAddr());
								log.setTo_addr(keyvalueService.getInAddr());
						    	log.setCtime(DateUtils.getSystime());
						    	sysLogService.add(log);
						    }
						    
						}catch(Exception e){
							//不做处理,继续归集
							e.printStackTrace();
							SysLog log=new SysLog();
							log.setFrom_addr(addr.getAddr());
							log.setTo_addr(keyvalueService.getInAddr());
					    	log.setSlog(e.getMessage());
					    	log.setCtime(DateUtils.getSystime());
					    	sysLogService.add(log);
						}
					}
				
					OperationLog log=new OperationLog();
					log.setContent("归集用户USDT");
					log.setCreate_time(DateUtils.getSystime());
					log.setIp(MacUtil.getUserIP(request));
					log.setUser_id(0);
					try{
					    Subject subject = SecurityUtils.getSubject();
					    User user=(User)subject.getPrincipal();
					    log.setUser_id(user.getId());
					}catch(Exception e){
						e.printStackTrace();
					}
					operationLogService.add(log);
					
				}
			});
			goverThread.start();
		}catch(Exception e){
			e.printStackTrace();
		    return error(ErrorInfo.InternalError);
		}
		return success();
	}
	
	
}
